import 'package:get/get.dart';
import 'package:ichineseaplus/domain/core/exceptions/user_not_found.exception.dart';
import 'package:ichineseaplus/domain/core/utils/snackbar.util.dart';
import 'package:ichineseaplus/infrastructure/navigation/bindings/domains/auth.repository.binding.dart';
import 'package:ichineseaplus/infrastructure/navigation/routes.dart';
import 'package:ichineseaplus/presentation/shared/loading/loading.controller.dart';
import 'package:logger/logger.dart';
import 'package:reactive_forms/reactive_forms.dart';

class LoginController extends GetxController {
  final repository = AuthRepositoryBinding().repository;
  final loadingController = Get.find<LoadingController>();

  final loginForm = FormGroup({
    'loginName': FormControl<String>(),
    'password': FormControl<String>(),
  }).obs;

  Future<void> login() async {
    try {
      loadingController.isLoading = true;
      await repository.authenticateUser(
        loginName: loginForm.value.control('loginName').value,
        password: loginForm.value.control('password').value,
      );
      loadingController.isLoading = false;
      Logger().v('Succuss Login!');

      await Get.offAndToNamed([Routes.ICA, Routes.STUDENT].join());
      Logger().v('Return token');
    } on UserNotFoundException {
      loadingController.isLoading = false;
      SnackbarUtil.showWarning(message: UserNotFoundException().toString());
    } catch (e) {
      loadingController.isLoading = false;
      Logger().e(e);
      SnackbarUtil.showError(message: e.toString());
    }
  }
}
